# filename： word_freq.py
# 阅读注释，在所有pass处删除pass，添加代码

from string import punctuation
import io

def process_file(dst):     # 读文件到缓冲区
    try:     # 打开文件
        f = open(dst, 'r')
    except IOError as s:
        print (s)
        return None
    try:     # 读文件到缓冲区
        bvffer = f.read()
        
    except:
        print ("Read File Error!")
        return None
    f.close()
    return bvffer


def process_buffer(bvffer):
    if bvffer:
        word_freq = {}
        bvffer = bvffer.lower()
        for ch in '“‘!;,.?”': 
        # 下面添加处理缓冲区 bvffer代码，统计每个单词的频率，存放在字典word_freq
        
         bvffer = bvffer.replace(ch, " ")
        words = bvffer.strip().split()
        for word in words:
            word_freq[word] = word_freq.get(word, 0) + 1

        return word_freq


def output_result(word_freq):
    if word_freq:
        sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
        for item in sorted_word_freq[:10]:  # 输出 Top 10 的单词
            print("词:%-5s 频:%-4d " % (item[0], item[1]))

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('dst')
    args = parser.parse_args()
    dst = args.dst
    bvffer = process_file(dst)
    word_freq = process_buffer(bvffer)
    output_result(word_freq)
